#include "template.hpp"
using namespace learn::templateTest;

template <class T>
void Stack<T>::push(T const &elem)
{
    // 追加传入元素的副本
    elems.push_back(elem);
}

template <class T>
void Stack<T>::pop()
{
    if (elems.empty())
    {
        throw out_of_range("Stack<>::pop(): empty stack");
    }
    // 删除最后一个元素
    elems.pop_back();
}

template <class T>
T Stack<T>::top() const
{
    if (elems.empty())
    {
        throw out_of_range("Stack<>::top(): empty stack");
    }
    // 返回最后一个元素的副本
    return elems.back();
}

void learn::templateTest::templateTest(void) // 函数名和命名空间名一致，要手动指定函数命令空间
{
    int i = 39;
    int j = 20;
    cout << "----------------------" << endl;
    cout << "Max(i, j): " << Max<int>(i, j) << endl;

    double f1 = 13.5;
    double f2 = 20.7;
    cout << "Max(f1, f2): " << Max<double>(f1, f2) << endl;

    string s1 = "Hello";
    string s2 = "World";
    cout << "Max(s1, s2): " << Max<string>(s1, s2) << endl;
    try
    {
        // 这里用的是Max的T R实现
        double s3 = 22.4;
        int s4 = 12;
        cout << "Max(s1, s2): " << Max<double, int>(s3, s4) << endl;
    }
    catch (exception const &e)
    {
        cerr << e.what() << endl;
    }
    try
    {
        Stack<int> intStack;       // int 类型的栈
        Stack<string> stringStack; // string 类型的栈

        // 操作 int 类型的栈
        intStack.push(7);
        cout << intStack.top() << endl;

        // 操作 string 类型的栈
        stringStack.push("hello");
        cout << stringStack.top() << std::endl;
        stringStack.pop();
        stringStack.pop();
    }
    catch (exception const &ex)
    {
        cerr << "Exception: " << ex.what() << endl;
        cout << "----------------------" << endl;
        return;
    }
}